import 'package:flutter/material.dart';
import 'package:sharing/net/net_util.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:dio/dio.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:meta/meta.dart';
import 'package:sharing/model/own_book_list.dart';
import 'package:sharing/resources/styles.dart';
import 'package:sharing/ui/my/book_list_detail.dart';
import 'package:sharing/ui/widget/user_login.dart';

class MyBookLists extends StatefulWidget {
  MyBookLists({Key key}) : super(key: key);

  _MyBookListsState createState() => _MyBookListsState();
}

class _MyBookListsState extends State<MyBookLists> {
  List _own_book_lists = [];

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        appBar: AppBar(
          title: Text("书单"),
          elevation: 0.0,
        ),
        body: Container(
          child: ListView.builder(
            itemCount: _own_book_lists.length,
            itemBuilder: (BuildContext context, int index) {
              return _OwnBookItem(
                ownBookList: _own_book_lists[index],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchBookList();
  }

  // 获取用户书单
  void _fetchBookList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");

    NetUtil.originGet(
        WholeApis.hostName + RisReadApis.ownBookList,
        Options(
          headers: {"Authorization": authorization},
        ), (Response response) {
      // print("data ${response.data}");
      print("statusCode ${response.statusCode}");
      //  var decoder = JsonDecoder();
      //  var mapData=   json.decode(response.data);
      // var mapData = decoder.convert(response.data);
      var data = json.encode(response.data);
      var mapData = json.decode(data);
      var code = mapData['code'];
      if (code == WholeApis.loginOutTime){
        print("用户登录过期");
         cleanAuth();
         Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context){
           return Login();

         },),);
        return ;
      } else if (code == WholeApis.permissionDefined){
        print("用户权限不足");
        return;
      } else if (code == WholeApis.paramsErr){
        print("参数错误");
        return ;
      }

       print("data =>> $data");
     // mapData = json.decode(mapData["message"]);
      mapData = mapData['message'];
      _own_book_lists.clear();
      mapData.forEach((o) {
        OwnBookList ownBookList = OwnBookList();
        // print("data $o");
        ownBookList.id = o["id"];
        ownBookList.name = o["name"];
        ownBookList.publish = o["publish"];
        ownBookList.instruction = o["instruction"];
        ownBookList.publishTime = DateTime.parse(o["publish_time"]);
        //  ownBookList.publishTime = new DateTime(o["publish_time"]);

        _own_book_lists.add(ownBookList);
      });
      setState(() {});
    });
  }

  void cleanAuth()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
   // String authorization = await prefs.getString("authorization");
    await  prefs.remove("authorization");
  }
}

class _OwnBookItem extends StatelessWidget {
  final OwnBookList ownBookList;

  _OwnBookItem({Key key, @required this.ownBookList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Card(
        child: Container(
        margin:
            const EdgeInsets.only(left: 4.0, right: 4.0, top: 2.0, bottom: 4.0),
        child: Row(
          children: <Widget>[
            SizedBox(
              height: 75,
              width: 100,
              child: Container(
                padding: const EdgeInsets.all(4.0),
                child: Image.network(
                WholeApis.hostName +"/static/img/9p.jpg",
               // "http://9p.cat-v.org/9p.jpg",//
                fit: BoxFit.cover,
              ),
              ),
            ),
            Expanded(
              child: Container(
                margin: const EdgeInsets.only(left: 4.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(
                        top: 4.0,
                        bottom: 4.0,
                      ),
                      child: Text(
                        ownBookList.name,
                        style: TextStyle(fontSize: 18,fontWeight: FontWeight.normal),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 4.0),
                      child: Text(ownBookList.instruction,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 14,fontWeight: FontWeight.normal)),
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(vertical: 4.0),
                      child: Text(
                        ownBookList.publish ? "公开" : "个人",
                        style: TextStyle(fontSize: 11.0),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      ),
      onTap: () {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (context) => BookListDetail(
                  ownBookList: ownBookList,
                ),
          ),
        );
      },
    );
  }
}
